#!/bin/bash

# 默认值
project_folder=""
skip_folders=()
whitelist_file=""

frameworks=()

# 解析参数
while [[ $# -gt 0 ]]; do
    key="$1"
    case $key in
        -project)
            project_folder="$2"
            shift
            shift
            ;;
        -skip)
            shift
            while [[ $# -gt 0 && ! $1 == -* ]]; do
                skip_folders+=("$1")
                shift
            done
            ;;
        -whitelist_file)
            whitelist_file="$2"
            shift
            shift
            ;;
        -h)
            echo "帮助文档："
            echo "-project <project文件夹> : 指定项目文件夹"
            echo "-skip <文件夹1 文件夹2 ...> : 指定要跳过的文件夹数组"
            echo "-whitelist_file framework white list"
            echo "-h : 显示帮助文档"
            exit 0
            ;;
        *)
            echo "未知参数: $1"
            exit 1
            ;;
    esac
done

# 检查必要参数
if [[ -z $project_folder ]]; then
    echo "请指定项目文件夹"
    exit 1
fi

if [[ -z $whitelist_file ]]; then
    echo "whitelist can't empty"
    exit 1
fi


# 读取白名单json文件内容
whitelist_json=$(cat $whitelist_file)

# 使用 jq 解析 JSON 为数组
whitelist=$(echo "$whitelist_json" | jq -r '.frameworks[]')

echo $whitelist
#scan_folder project_folder
#echo $frameworks

source_files=$(find $project_folder -type d \( -name "$skip_folders" \) -prune -o -type f -name "*.swift" -print)

for file in $source_files
do
    frameworks=$(grep -oE 'import\s+[A-Za-z0-9_]*' "$file" | awk '{for(i=2; i<=NF; i++) print $i}')
 #   echo $frameworks
    for framework in $frameworks
    do
      #  echo $framework
        found=false
        for item in $whitelist; do
            echo $item
            if [ $item = $framework ]; then
                echo "framework 合法"
                found=true
                break
            fi
        done

        if [ $found = false ]; then
            line=$(grep -n "import $framework" "$file" | cut -d: -f1)
            echo "$file:$line have exist invalid framework: $framework"
            exit 1
        fi
    done
done

